package com.supermap.qdsearch.fragment;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.bumptech.glide.Glide;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.supermap.qdsearch.R;
import com.supermap.qdsearch.adapter.SwipeAdapter;
import com.supermap.qdsearch.entity.CollectBean;
import com.supermap.qdsearch.utils.ConstUtils;
import com.supermap.qdsearch.utils.FileProvider7;
import com.supermap.qdsearch.utils.NetUtils;
import com.supermap.qdsearch.utils.SelectImgUtil;
import com.supermap.qdsearch.utils.TimeUtils;
import com.supermap.qdsearch.utils.ToastUtils;
import com.supermap.qdsearch.widget.CustomListView;
import com.supermap.qdsearch.widget.CustomPopWindow;
import com.supermap.qdsearch.widget.CustomProgressBar;
import com.supermap.qdsearch.widget.SwipeLayoutManager;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.StringRequest;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class CheckFragment extends Fragment implements View.OnClickListener {


    Unbinder unbinder;
    @BindView(R.id.listview)
    CustomListView listview;
    @BindView(R.id.close)
    ImageButton close;
    @BindView(R.id.pull)
    PullToRefreshScrollView pull;


    private List<CollectBean> list;
    private SwipeAdapter swipeAdapter;
    private String getUrl;
    private CustomProgressBar dialog;
    private int pageIndex = 1;
    private ImageView tpivImg;
    private CustomPopWindow popChooseWindow;
    private File file;
    private CustomPopWindow inspectionPopWindow;

    public CheckFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_check, container, false);
        unbinder = ButterKnife.bind(this, view);
        list = new ArrayList();
        getUrl = getResources().getString(R.string.test);
        if (listview != null) {
            dialog = new CustomProgressBar(getContext());
            dialog.show();
            initData();
            initLv();
        }
        close.setOnClickListener(this);
        return view;
    }


    public void initLv() {
        //设置刷新模式 ，both代表支持上拉和下拉，pull_from_end代表上拉，pull_from_start代表下拉
        pull.setMode(PullToRefreshBase.Mode.BOTH);

        pull.setOrientation(LinearLayout.VERTICAL);
/*这里通过getLoadingLayoutProxy 方法来指定上拉和下拉时显示的状态的区别，第一个true 代表下来状态 ，第二个true 代表上拉的状态
如果想区分上拉和下拉状态的不同，可以分别设置*/

        ILoadingLayout startLabels = pull.getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("下拉刷新");
        startLabels.setRefreshingLabel("正在载入...");
        startLabels.setReleaseLabel("放开刷新");


        ILoadingLayout endLabels = pull.getLoadingLayoutProxy(false, true);
        endLabels.setPullLabel("上拉刷新");
        endLabels.setRefreshingLabel("正在载入...");
        endLabels.setReleaseLabel("放开刷新...");
        //3.设置监听事件
        pull.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                addtoTop();//请求网络数据，并更新listview组件
                refreshComplete();//数据加载完成后，关闭header,footer
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                addtoBottom();//请求网络数据，并更新listview组件
                refreshComplete();//数据加载完成后，关闭header,footer
            }
        });
    }

    //数据引用的方法
    public void initData() {

        StringRequest request = new StringRequest(getUrl);

        request.add("page", pageIndex);

        new NetUtils<Object>(request) {
            @Override
            public Object onSuccess(Response<String> response) {
                String s = response.get();
                if (s != null)
                    //添加到大集合对象中
                    list.add(new CollectBean());
                //设置适配器
                setAdapter();
                dialog.dismiss();
                return null;
            }

            @Override
            public Object onFail(Response<String> response) {
                ToastUtils.showShortToast("请检查网络~");
                return null;
            }
        };
    }


    //下拉刷新的方法:
    public void addtoTop() {

        pageIndex = 1;
        list.clear();
        loadData();
    }

    public void loadData() {

        StringRequest request = new StringRequest(getUrl);

        request.add("page", pageIndex);

        new NetUtils<Object>(request) {
            @Override
            public Object onSuccess(Response<String> response) {
                String s = response.get();
                if (s != null)
                    list.add(new CollectBean());
                //设置适配器
                setAdapter();

                return null;
            }

            @Override
            public Object onFail(Response<String> response) {
                ToastUtils.showShortToast("请检查网络~");
                return null;
            }
        };
    }

    //上拉加载的方法:
    public void addtoBottom() {
        pageIndex++;
        loadData();

    }

    //设置适配器的方法:
    public void setAdapter() {
        if (swipeAdapter == null) {
            swipeAdapter = new SwipeAdapter(list, getContext(), ConstUtils.SEARCH_STATE);
            swipeAdapter.setOnClickListener(new SwipeAdapter.OnClickListener() {
                @Override
                public void onCheckClick(int position) {
                    onViewClicked();
                }

                @Override
                public void onRepairClick(int position) {

                }

                @Override
                public void onVerifyClick(int position) {

                }

                @Override
                public void onInfoClick(int position) {

                }

                @Override
                public void onEditClick(int position) {

                }

                @Override
                public void onDeleteClick(int position) {

                }
            });
            if (listview != null) {
                listview.setAdapter(swipeAdapter);
                listview.setOnScrollListener(new AbsListView.OnScrollListener() {
                    @Override
                    public void onScrollStateChanged(AbsListView view, int scrollState) {
                        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
                            //如果垂直滑动，则需要关闭已经打开的layout
                            SwipeLayoutManager.getInstance().closeCurrentLayout();
                        }
                    }

                    @Override
                    public void onScroll(AbsListView view, int firstVisibleItem,
                                         int visibleItemCount, int totalItemCount) {
                    }
                });
            }

        } else {
            //当adapter的数据全部清除完成后调用该方法 防止下标越界异常
            swipeAdapter.notifyDataSetInvalidated();
        }

    }

    /**
     * 刷新完成时关闭
     */
    public void refreshComplete() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (pull != null)
                    pull.onRefreshComplete();
            }
        }, 1000);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        SwipeLayoutManager.getInstance().clearCurrentLayout();
    }

    @Override
    public void onPause() {
        super.onPause();
        SwipeLayoutManager.getInstance().clearCurrentLayout();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0) {
            if (data.getData() != null) {
                String mediaPath = SelectImgUtil.getMediaPath(getContext(), data.getData());
                Glide.with(getContext()).load(mediaPath).into(tpivImg);
                if (popChooseWindow != null)
                    popChooseWindow.dissmiss();
            }
        } else if (requestCode == 1) {
                Glide.with(getContext()).load(file.getAbsolutePath()).into(tpivImg);
                if (popChooseWindow != null)
                    popChooseWindow.dissmiss();
        } else {
            addtoTop();
            refreshComplete();
        }

    }

    public void onViewClicked() {
        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.window_inspection_fill, null);

        CustomPopWindow.PopupWindowBuilder popupWindowBuilder = new CustomPopWindow.PopupWindowBuilder(getContext());
        inspectionPopWindow = popupWindowBuilder.setView(inflate).setOutsideTouchable(true).enableBackgroundDark(true).create();
        inspectionPopWindow.showAtLocation(getView(), Gravity.BOTTOM, 0, 0);

        tpivImg = inflate.findViewById(R.id.tpiv_img);
        tpivImg.setOnClickListener(this);
        inflate.findViewById(R.id.bt_confirm).setOnClickListener(this);
        inflate.findViewById(R.id.bt_cancel).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tpiv_img:
                View view = LayoutInflater.from(getContext()).inflate(R.layout.pop_choose, null);
                CustomPopWindow.PopupWindowBuilder popupWindowBuilder = new CustomPopWindow.PopupWindowBuilder(getContext());
                popupWindowBuilder.setOutsideTouchable(true);
                popupWindowBuilder.enableBackgroundDark(true);
                popupWindowBuilder.size(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                popChooseWindow = popupWindowBuilder.setView(view).create();
                popChooseWindow.showAtLocation(getView(), Gravity.BOTTOM, 0, 0);
                view.findViewById(R.id.bt_capture).setOnClickListener(this);
                view.findViewById(R.id.bt_photo).setOnClickListener(this);
                break;
            case R.id.bt_capture:
                try {
                    file = new File(getContext().getExternalCacheDir(), TimeUtils.date2String(new Date()));
                    if (file.exists()) {
                        file.delete();
                    }
                    file.createNewFile();
                    Uri uri = FileProvider7.getUriForFile(getContext(), file);
                    Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent1.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    startActivityForResult(intent1, 1);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            case R.id.bt_photo:
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent, 0);
                break;
            case R.id.bt_confirm:
                ToastUtils.showShortToast("巡检成功");

                break;
            case R.id.bt_cancel:
                if(inspectionPopWindow!=null){
                    inspectionPopWindow.dissmiss();
                }
                break;
            case R.id.close:
                getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
                break;
        }
    }
}
